<script setup lang="ts">
import {Top,CreditCard,Bottom,Printer,Search,Operation, Grid} from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
import {ElMessageBox } from 'element-plus'
import {ref,onBeforeMount} from "vue";
//@ts-ignore
import {
  uploadFileApi,
  mkidrFolderApi,
  checkFileParam,
  findFileDatasApi,
  findFolderInfosApi,
  checkFileUploadStatusApi,
  searchFilesApi,
  checkRecycleType,

} from "./FileApi"
import {getFileMD5} from "../../utils/Md5Utils.ts";
import FileShow from "./common/FileShow.vue";
import Folder from "./common/Folder.vue";
import {digElMessage} from '../../common/Message.ts'



//父文件夹ID
let parentId=ref("")
//当前文件夹ID
let coureentFolderId=ref("")

//存储文件元数据
let filesData=ref([]);

//存储文件夹元数据
let foldersData=ref([]);
const getFileData=async ()=>{
  await   findFileDatasApi({
    folderId:coureentFolderId.value,
    parentId:coureentFolderId.value,

  }).then(res=>{
    filesData.value=res.data.files
    foldersData.value=res.data.folders
  }).catch(error=>{
    console.log(error)
  })
}


//搜索文件
let searchFileName=ref('')

const searchFile=async (searchFileName)=>{
  if (searchFileName!='')
  {
    await searchFilesApi(searchFileName).then(res=>{
      filesData.value=res.data.files
      foldersData.value=res.data.folders
    })
  }
  else{
    await getFileData()
  }
}

onBeforeMount(()=>{
  getFileData();
})




//控制进度条
let controlerProcess=ref(false);


const customColor = ref('#409eff')
let percentageValue = ref(0)


let showFilText=ref("计算文件中")




/**
 * 检查文件上传进度
 */
const _checkFIleUploadStatus=  (data: checkFileParam,timeForFIle:unknown):Promise<boolean>=>{
  return new Promise(async resolve => {
    await checkFileUploadStatusApi(data).then(res=>{
        if(res.data==1){
          //@ts-ignore
          clearTimeout(timeForFIle)
          resolve(true)
        }

     else{
        //@ts-ignore
        clearTimeout(timeForFIle)
          controlerProcess.value=false
        digElMessage("文件已经上传请勿重复上传","warning",1000);
          resolve(false)
      }

    })
  })

}
let showValue=ref(0)
//实时文件上传进度的百分比 = parseInt((e.loaded / e.total) * 100);
//@ts-ignore
const onUploadProgress = (e) => {
  //@ts-ignore
  percentageValue.value=parseInt((e.loaded / e.total) * 100)
}
const _uploadFile=async (data:any)=>{
  await uploadFileApi(data,onUploadProgress).then(async res=>{
    controlerProcess.value=false

    //@ts-ignore
    if(res.code=='00000'){
      digElMessage("上传文件成功","success",1000);
      await  updateData();
    }
    else{

      digElMessage("上传文件失败","error",1000);
      }
  })
}

const _iniTimeFun=()=>{

  if(percentageValue.value>90){
    percentageValue.value=80;
  }
  if(percentageValue.value>80){
    percentageValue.value=percentageValue.value+1;
  }
  else{
    percentageValue.value+=2
  }
}

//上传一次50M
let fileMaxSize=1024*1024*50
const beforeUpload=async (e:any)=>{

  if(e.size>fileMaxSize){
      digElMessage("文件大小超出限制,最大为20M","warning",1500)

    return false;

  }

 else{
    controlerProcess.value=true
    let  timeForFIle= setInterval(() => {_iniTimeFun();}, 100)

    //获取MD5
    await getFileMD5(e).then( async md5 => {
      //检验文件
      _checkFIleUploadStatus({fileMd5:md5,fileName:e.name,folderId:coureentFolderId.value},timeForFIle)
          .then(async res=>{
                if(res){
                  showFilText.value="上传文件中"
                  percentageValue.value=0;
                  let formData = new FormData();
                  formData.append("fileMd5",md5 as string);
                  formData.append("folderId",coureentFolderId.value);
                  formData.append("file",e);
                  //上传文件
                  await  _uploadFile(formData);
                  showFilText.value="计算文件MD5"
                  percentageValue.value=0;
                  showValue.value=0
                }
              }
          )
    })


    return false;
  }

}



const mkdirFolder=()=>{
  ElMessageBox.prompt('请输入文件夹名称', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    //@ts-ignore,

  })
      .then(({ value }) => {
        mkidrFolderApi({parentId:coureentFolderId.value,folderName:value}).then(res=>{
          if(res.code=="00000"){
            digElMessage('创建文件夹成功','success',1000)
            getFileData();

          }
        })
      })
      .catch(() => {
        digElMessage('取消','info',1000)

      })
}

//接受子组件的folderid

const changeFolder=(e:string)=>{
  parentId.value=coureentFolderId.value;

  coureentFolderId.value=e;

  getFileData();
}



//返回上一级
const roback=()=>{
  if( coureentFolderId.value==""){
    ElNotification({
      title: 'ERROR',
      message: '已经是根目录',
      type: 'error',
    })
  }
  else{
    findFolderInfosApi(coureentFolderId.value).then(res=>{
      coureentFolderId.value=res.data.parentID
      getFileData()

    })
  }

}

const updateData=async ()=>{
  await getFileData()
}

const uploadFolder=async ()=>{
  await getFileData()
}

</script>

<template>

  <el-dialog v-model="controlerProcess"  width="466">

    <el-progress
        type="line"
        :duration="8"

        :percentage="percentageValue"
        :stroke-width="8"
        status="success"
        :color="customColor" >

      <el-text type="primary">{{showFilText}}</el-text>
    </el-progress>

  </el-dialog>

  <div class="file" >
    <div class="file_head">
      <div class="file_head_left">
        <el-upload
            ref="uploadRef"
            class="upload-demo"
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            :before-upload="beforeUpload"
        >
          <el-button :icon="Top" >
            <el-text type="primary">上传文件</el-text>
          </el-button>
        </el-upload>

        <el-button :icon="CreditCard"  style="margin-left: 20px">
          <el-text type="primary" @click="mkdirFolder"> 新建文件夹</el-text>
        </el-button>

        <el-button :icon="Bottom" >
          <el-text type="primary"> 离线下载</el-text>
        </el-button>

        <el-button :icon= "Printer" ><el-text type="primary" @click="roback"> 返回上一级</el-text>
        </el-button>
      </div>


      <div class="file_head_right">

          <el-input
            style="width: 200px"
            placeholder="请搜索您的文件"
            v-model="searchFileName"
            clearable
          >
            <template #suffix>
              <el-icon class="el-input__icon" @click="searchFile(searchFileName) " ><search /></el-icon>
            </template>
          </el-input>



      </div>

    </div>

    <div class="file_infos" >
      <div v-for="(item,index) in filesData" :key="index"  style="text-align: center">
        <FileShow :fileInfo="item"  @updateData="updateData"/>
      </div>

      <!--      :xl="4" :lg="4" :md="8" :sm="12" :xs="12"-->
      <div v-for="(folder,index) in foldersData" :key="index"  style="text-align: center">
        <Folder :folderInfo="folder" @changeFolder="changeFolder" @uploadFolder="uploadFolder"/>
      </div>
    </div>


  </div>




</template>

<style scoped lang="less">
.el-progress--line {
  margin-bottom: 15px;
  width: 430px;
}
.el-progress{

}

.file{
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;


  .file_infos{
    display: flex;
    flex-wrap: wrap;
    height: 420px;
    margin-top: 50px;
    overflow: auto;
  }

  .file_infos::-webkit-scrollbar {
    width: 1px;
    height: 2px;
  }

  .file_infos::-webkit-scrollbar-button {
    background-color: #ffffff;
  }

  .file_infos::-webkit-scrollbar-track-piece {
    background: #ffffff;
  }

  .file_infos::-webkit-scrollbar-thumb {
    background: #ffffff;
    border-radius: 1px;
  }
  .file_head{
    height: 40px;
    display: flex;
    position: fixed;
    left: 220px;
    top:70px;
    width: 100%;
    z-index: 10;
    .file_head_left{
      margin-right: 450px;
      display: flex;
    }
    .file_head_right{
      .el-input{
        margin-right: 13px;
      }
      .el-button{
        font-size: 24px;
        margin-right: 0;
        color: skyblue;


      }
    }
  }
}

</style>